<template>
  <div class="xtx-pagination">
    <a v-if="myCurrentPage > 1" @click="changePager(myCurrentPage - 1)" href="javascript:;">上一页</a>
    <a v-else href="javascript:;" class="disabled">上一页</a>
    <span v-if="pager.start > 1">...</span>
    <a href="javascript:;" @click="changePager(i)" :class="{active:i === myCurrentPage}" v-for="i in pager.btnArr" :key="i">{{i}}</a>
    <span v-if="pager.end < pager.pageCount">...</span>
    <a v-if="myCurrentPage < pager.pageCount" @click="changePager(myCurrentPage + 1)" href="javascript:;">下一页</a>
    <a v-else  href="javascript:;" class="disabled">下一页</a>
  </div>
</template>

<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'XtxPagination',
  props: {
    total: {
      type: Number,
      default: 100
    },
    currentPage: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 10
    }
  },
  setup (props, { emit }) {
    // 总条数
    const pageTotal = ref(100)
    // 每页条数
    const pageSize = ref(10)
    // 当前所在页
    const myCurrentPage = ref(1)
    // 按钮个数
    const btnCount = 5
    // 根据以上数据得到（总页数，起始页码，结束页码，按钮数组）
    const pager = computed(() => {
      // 计算总页数 = 总条数 / 每一页条数  向上取整
      const pageCount = Math.ceil(pageTotal.value / pageSize.value)
      // 计算起始页和结束页
      // 理想情况根据当前页码和按钮个数可得到
      let start = myCurrentPage.value - Math.floor(btnCount / 2)
      let end = start + btnCount - 1
      // 如果起始页码小于1了，需要重新计算
      if (start < 1) {
        start = 1
        end = (start + btnCount - 1) > pageCount ? pageCount : (start + btnCount - 1)
      }
      // 如果结束页码大于总页数，需要重新计算
      if (end > pageCount) {
        end = pageCount
        start = (end - btnCount + 1) < 1 ? 1 : (end - btnCount + 1)
      }
      // 处理完毕start和end得到按钮数组
      const btnArr = []
      for (let i = start; i <= end; i++) {
        btnArr.push(i)
      }
      return { pageCount, start, end, btnArr }
    })
    // 监听props的变化，更新组件内部数据
    watch(props, () => {
      pageTotal.value = props.total
      pageSize.value = props.pageSize
      myCurrentPage.value = props.currentPage
    }, { immediate: true })
    // 切换分页函数
    const changePager = (newPage) => {
      if (myCurrentPage.value !== newPage) {
        myCurrentPage.value = newPage
        // 通知父组件更新页码
        emit('current-change', newPage)
      }
    }
    return { pager, myCurrentPage, changePager }
  }
}
</script>

<style lang="less" scoped>
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
